package com.shouhuobao.bhi.receiver;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.tools.CameraManager;
import com.collectplus.express.view.CameraSurfaceView;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import droid.frame.activity.title.TitleRes;
import droid.frame.utils.android.Log;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.Str;

/**
 * Created by joker on 2017/10/30.
 * 选择系统相册，任意比例裁剪，拍照完成后，进行裁剪
 */
public class ReceiverCameraActivity2 extends BaseActivity2 implements View.OnClickListener {

    private CameraSurfaceView mCameraSurface;
    // 拍照后的界面
    private ImageView mCaptureImage;
    // 检测屏幕转动方向
    private MyOrientationDetector orientationDetector;
    /**
     * 当前屏幕的旋转角度 -- 实时, 0代表手机竖屏时的正常显示, 90代表手机顶端朝右,以此类推
     */
    private int rotate = 0;
    private String capturePath;// 拍照路径
    private View mImageLayout;

    @SuppressLint({"ResourceAsColor", "MissingSuperCall"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBarColor(R.color.app_capture_status);
        super.onCreate(savedInstanceState);
        orientationDetector = new MyOrientationDetector(this);
    }

    public class MyOrientationDetector extends OrientationEventListener {
        public MyOrientationDetector(Context context) {
            super(context);
        }

        /**
         * @param orientation 0-359
         */
        @Override
        public void onOrientationChanged(int orientation) {
            if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
                return;
            }
            Log.i("receiver_camera ", "onOrientationChanged:" + orientation);

            if (orientation > 315 || orientation > 0 && orientation < 45) {
                rotate = 0;
            } else if (orientation > 45 && orientation < 135) {
                rotate = 90;
            } else if (orientation > 135 && orientation < 215) {
                rotate = 180;
            } else if (orientation >= 215 && orientation < 315) {
                rotate = 270;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        orientationDetector.enable();
    }

    @Override
    protected void onStop() {
        super.onStop();
        orientationDetector.disable();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.parcel_camera);
        super.findViewById();
        final ImageView rightTitle = (ImageView) findViewById(R.id.title_right_image);
        getAppTitle().setTitle(new TitleRes(R.drawable.title_back_2_selector, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }), new TitleRes("为要识别的图片拍照"), new TitleRes(R.drawable.title_flashlight_on, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 默认打开
                if (rightTitle.getTag() == null) {
                    rightTitle.setImageResource(R.drawable.title_flashlight_off_press);
                    rightTitle.setTag("");
                    Camera.Parameters parameters = mCameraSurface.getCamera().getParameters();
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                    mCameraSurface.getCamera().setParameters(parameters);
                } else {
                    rightTitle.setImageResource(R.drawable.title_flashlight_on);
                    rightTitle.setTag(null);
                    Camera.Parameters parameters = mCameraSurface.getCamera().getParameters();
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
                    mCameraSurface.getCamera().setParameters(parameters);
                }
            }
        }));
        setTitleBackgroundColor(getResources().getColor(R.color.app_capture_status));
        ((TextView) findViewById(R.id.title_middle_text)).setTextColor(Color.WHITE);
        ((TextView) findViewById(R.id.tmp_tip)).setText("请拍摄要识别的图片");
        mCameraSurface = (CameraSurfaceView) findViewById(R.id.parcel_camera);
        // mCameraSurface.getHolder().setFixedSize(100, 100);
        mCaptureImage = (ImageView) findViewById(R.id.parcel_image);
        mImageLayout = findViewById(R.id.parcel_image_layout);
        findViewById(R.id.parceL_gallery).setOnClickListener(this);
        findViewById(R.id.parceL_camera).setOnClickListener(this);
        findViewById(R.id.parceL_camera_cancel).setOnClickListener(this);
        findViewById(R.id.parceL_camera_sure).setOnClickListener(this);
    }

    /**
     * 大图片保存路径
     */
    String tempUri = "file:///sdcard/temp.jpg";

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        // 从相册中选择图片
        if (requestCode == 1001 && data != null) {
            // String file = new IntentUtils().getPicturePath(getContext(), data.getData());
            // Bitmap compressBmp = BitmapUtils.compressBySize(file);
            //
            Bundle extras = data.getExtras();
            Uri imageUri = Uri.parse(tempUri);
            if (imageUri != null) {
                Bitmap bitmap = decodeUriAsBitmap(imageUri);
                if (bitmap != null) {
                    setImageLayout(bitmap);
                    saveBitmapToFile(bitmap, null);
                }
            }
            if (extras != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Bitmap bitmap = extras.getParcelable("data");
                if (bitmap != null) {
                    setImageLayout(bitmap);
                    saveBitmapToFile(bitmap, null);
                }
            }
        } else if (requestCode == 1002) {//系统选择照片返回
            Uri uri = null;
            if (data != null) {
                uri = data.getData();
                if (uri != null) {
                    CameraManager.getInstance().cuttingWithXY(this, uri.toString(), tempUri, 0, 0);
                }
            }
        }
    }

    /**
     * 根据图片Url，返回Bitmap
     *
     * @param uri
     * @return
     */
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    private void tackPreviewPicture() {
        byte[] data = mCameraSurface.getPreviewData();
        Camera camera = mCameraSurface.getCamera();
        Camera.Size size = camera.getParameters().getPreviewSize();
        try {
            YuvImage image = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
            if (image != null) {
                Log.d("22222", image.getWidth() + "********" + image.getHeight());
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compressToJpeg(new Rect(0, 0, size.width, size.height), 100, stream);
                Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
                // 如果图片旋转了, 则校正
                // rotateDegree = -90;
                int rotateDegree = (rotate + 90) % 360;
                if (rotateDegree != 0) {
                    Bitmap rotateBitmap = BitmapUtils.toRotation(bmp, rotateDegree);
                    saveBitmapToFile(rotateBitmap, null);// 保存到本地存储卡
                    //                    setImageLayout(rotateBitmap);
                } else {
                    saveBitmapToFile(bmp, null);// 保存到本地存储卡
                    //                    setImageLayout(bmp);
                }
                stream.close();
                if (Str.isNotEmpty(capturePath) && bmp != null) {
                    CameraManager.getInstance().cuttingWithOutput(this, Uri.fromFile(new File(capturePath)).toString(), tempUri, 0, 0, bmp.getWidth(), bmp.getHeight());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 从相册选取
            case R.id.parceL_gallery:
                CameraManager.getInstance().localPhoto(ReceiverCameraActivity2.this);
                break;
            // 拍照
            case R.id.parceL_camera:
                try {
                    // camera.takePicture(null, null, jpeg);
                    tackPreviewPicture();
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("请检查设备是否授权拍照权限");
                    finish();
                }
                break;
            // 重新拍照
            case R.id.parceL_camera_cancel:
                mImageLayout.setVisibility(View.GONE);
                mCameraSurface.getCamera().startPreview();
                break;
            // TODO 下一步
            case R.id.parceL_camera_sure:
                // AppCache.getParcelNew().setGoodsImage(capturePath);
                // startActivity(ReceiverTabFragmentActivity.class);
                Intent intent = new Intent();
                intent.putExtra("file", capturePath);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

    /**
     * 设置拍照或者从相册选取的图片
     *
     * @param bitmapImage
     */
    private void setImageLayout(Bitmap bitmapImage) {
        mImageLayout.setVisibility(View.VISIBLE);
        mCaptureImage.setImageBitmap(bitmapImage);
        mCaptureImage.setScaleType(ImageView.ScaleType.FIT_XY);
    }

    private void saveBitmapToFile(Bitmap compressBitmap, String filePath) {
        try {
            if (filePath == null) {
                File file = new File(AppConfig.getCaptureDir(), System.currentTimeMillis() + ".png");
                if (file.exists() == false) {
                    droid.frame.utils.lang.FileUtils.createNewFileOrDir(file.getPath());
                }
                filePath = file.getPath();
                capturePath = filePath;
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
            compressBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);// TODO
            // 1
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
